package com.ruoyi.farmwell.well.service.impl;


import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.farmwell.ghy.domain.SysGhy;
import com.ruoyi.farmwell.well.domain.SysWell;
import com.ruoyi.farmwell.well.mapper.SysWellMapper;
import com.ruoyi.farmwell.well.service.ISysWellService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * 机井信息Service业务层处理
 * 
 * @author ZJP
 * @date 2024-07-23
 */
@Service
public class SysWellServiceImpl implements ISysWellService
{
    @Autowired
    private SysWellMapper sysWellMapper;

    @Override
    public ByteArrayOutputStream insertQRCodeIntoTemplate(byte[] qrCodeBytes, String templateFilePath, SysWell well)throws IOException {
        try (Workbook workbook = new XSSFWorkbook(new FileInputStream(templateFilePath))) {
            Sheet sheet = workbook.getSheetAt(0);

            ByteArrayInputStream bis = new ByteArrayInputStream(qrCodeBytes);
            int pictureIdx = workbook.addPicture(qrCodeBytes, Workbook.PICTURE_TYPE_PNG);
            CreationHelper helper = workbook.getCreationHelper();
            Drawing drawing = sheet.createDrawingPatriarch();

            ClientAnchor anchor = helper.createClientAnchor();
            anchor.setCol1(5);
            anchor.setRow1(2);

            Picture pict = drawing.createPicture(anchor, pictureIdx);
            pict.resize();

            // 创建单元格并设置数据
            Row row = sheet.getRow(1);
            Cell cell = row.getCell(3);
            cell.setCellValue(well.getProjectYear());
            // 创建单元格并设置数据
            Row row1 = sheet.getRow(3);
            Cell cell1 = row1.getCell(1);
            cell1.setCellValue(well.getWellNumber());
            // 创建单元格并设置数据
            Row row2 = sheet.getRow(4);
            Cell cell2 = row2.getCell(1);
            cell2.setCellValue(well.getAddress());
            // 创建单元格并设置数据
            Row row3 = sheet.getRow(5);
            Cell cell3 = row3.getCell(1);
            cell3.setCellValue(null!=well.getGhyName()? well.getGhyName():"无");
            // 创建单元格并设置数据
            Row row4 = sheet.getRow(6);
            Cell cell4 = row4.getCell(1);
            cell4.setCellValue(null!=well.getGhyTel()? well.getGhyTel():"无");
            // 创建单元格并设置数据
            Row row5 = sheet.getRow(0);
            Cell cell5 = row5.getCell(0);
            cell5.setCellValue("商水县"+well.getCounty()+"农田水利设施管护标识牌");

            // 创建字体
            XSSFFont font = (XSSFFont) workbook.createFont();
            font.setBold(true);  // 设置加粗
            font.setFontHeightInPoints((short) 16);  // 设置字体大小

            // 创建单元格样式
            CellStyle style = workbook.createCellStyle();
            style.setFont(font);
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            cell5.setCellStyle(style);

            // 创建样式以实现居中对齐
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setBorderTop(BorderStyle.THIN);
            cellStyle.setBorderBottom(BorderStyle.THIN);
            // 设置单元格的文字换行
            cellStyle.setWrapText(true);
            // 应用样式到单元格
            cell.setCellStyle(cellStyle);
            cell1.setCellStyle(cellStyle);
            cell2.setCellStyle(cellStyle);
            cell3.setCellStyle(cellStyle);
            cell4.setCellStyle(cellStyle);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream;
        }
    }

    /**
     * 查询机井信息
     * 
     * @param id 机井信息主键
     * @return 机井信息
     */
    @Override
    public SysWell selectSysWellById(Long id)
    {
        return sysWellMapper.selectSysWellById(id);
    }

    /**
     * 查询机井信息列表
     * 
     * @param sysWell 机井信息
     * @return 机井信息
     */
    @Override
    public List<SysWell> selectSysWellList(SysWell sysWell)
    {
        return sysWellMapper.selectSysWellList(sysWell);
    }

    /**
     * 新增机井信息
     * 
     * @param sysWell 机井信息
     * @return 结果
     */
    @Override
    public int insertSysWell(SysWell sysWell)
    {
        sysWell.setCreateTime(DateUtils.getNowDate());
        return sysWellMapper.insertSysWell(sysWell);
    }

    /**
     * 修改机井信息
     * 
     * @param sysWell 机井信息
     * @return 结果
     */
    @Override
    public int updateSysWell(SysWell sysWell)
    {
        sysWell.setUpdateTime(DateUtils.getNowDate());
        return sysWellMapper.updateSysWell(sysWell);
    }

    /**
     * 批量删除机井信息
     * 
     * @param ids 需要删除的机井信息主键
     * @return 结果
     */
    @Override
    public int deleteSysWellByIds(Long[] ids)
    {
        return sysWellMapper.deleteSysWellByIds(ids);
    }

    /**
     * 删除机井信息信息
     * 
     * @param id 机井信息主键
     * @return 结果
     */
    @Override
    public int deleteSysWellById(Long id)
    {
        return sysWellMapper.deleteSysWellById(id);
    }

    @Override
    public List<TreeSelect> deptTreeWell(SysWell well) {
        List<SysWell> sysWells=sysWellMapper.selectSysWellList(well);
        Long i = Long.valueOf(0);
        TreeSelect root = new TreeSelect();
        root.setLabel("商水县");
        root.setId(i++);
        List<TreeSelect> treeSelects = buildTree(sysWells);
        root.setChildren(treeSelects);
        List<TreeSelect> rootNodes = new ArrayList<>();
        rootNodes.add(root);
        return rootNodes;

    }
    // 构建树形结构方法
    public static List<TreeSelect> buildTree(List<SysWell> ghyList) {
        // 存储镇及其对应的村
        Map<String, TreeSelect> townMap = new HashMap<>();
        List<TreeSelect> rootNodes = new ArrayList<>();
        // 自定义ID生成器
        IdGenerator townIdGenerator = new IdGenerator(10, 100);
        IdGenerator villageIdGenerator = new IdGenerator(100, 1000);
        // 使用Set来记录已添加的村名，确保唯一性
        Map<String, Set<String>> townVillages = new HashMap<>();

        for (SysWell ghy : ghyList) {
            String townName = ghy.getTown();  // 镇名
            String villageName = ghy.getCun();  // 村名

            // 跳过无效数据
            if (townName == null || townName.trim().isEmpty()) {
                continue;
            }

            // 确保镇节点存在
            TreeSelect townNode = townMap.computeIfAbsent(townName, name -> {
                Long townId = (long) townIdGenerator.nextId();
                TreeSelect node = new TreeSelect();
                node.setId(townId);
                node.setLabel(name);
                rootNodes.add(node);
                townVillages.put(name, new HashSet<>()); // 初始化该村的已添加村集合
                return node;
            });

            // 添加村节点到对应的镇（确保唯一性）
            if (villageName != null && !villageName.trim().isEmpty()) {
                Set<String> villages = townVillages.get(townName);

                // 如果村名不在集合中，添加新节点
                if (villages.add(villageName)) {
                    Long villageId = (long) villageIdGenerator.nextId();
                    TreeSelect villageNode = new TreeSelect();
                    villageNode.setId(villageId);
                    villageNode.setLabel(villageName);
                    townNode.addChild(villageNode);
                }
            }
        }

        return rootNodes;
    }
    // 自定义ID生成器
    static class IdGenerator {
        private final int min;
        private final int max;
        private int current;
        private final Set<Integer> usedIds = new HashSet<>();

        public IdGenerator(int min, int max) {
            this.min = min;
            this.max = max;
            this.current = min;
        }

        public int nextId() {
            // 如果已经用完所有ID，重置或抛出异常（根据需求选择）
            if (usedIds.size() >= (max - min)) {
                throw new IllegalStateException("ID池已耗尽");
            }

            // 尝试获取下一个可用ID
            int id = current++;
            if (current >= max) {
                current = min; // 循环使用
            }

            // 如果ID已被使用，寻找下一个可用ID
            if (usedIds.contains(id)) {
                id = findNextAvailableId();
            }

            usedIds.add(id);
            return id;
        }

        private int findNextAvailableId() {
            for (int i = min; i < max; i++) {
                if (!usedIds.contains(i)) {
                    return i;
                }
            }
            // 理论上不会执行到这里，因为已经检查过ID池是否已满
            throw new IllegalStateException("ID池已耗尽");
        }
    }
}
